package com.itcoon.cloud.framework.security.handler;

import com.itcoon.cloud.framework.ex.errorcode.IErrorCode;
import com.itcoon.cloud.framework.ex.register.IErrorCodeRegister;
import com.itcoon.cloud.framework.utils.SpringUtils;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * created in 2021/4/8
 */
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private static final Logger log = LoggerFactory.getLogger(DefaultAuthenticationFailureHandler.class);

    private final IErrorCodeRegister errorCodeRegister;

    public DefaultAuthenticationFailureHandler(IErrorCodeRegister errorCodeRegister) {
        this.errorCodeRegister = errorCodeRegister;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        IErrorCode errorCode = exception.getErrorCode();
        String message = errorCode != null ? errorCode.getMessage() : exception.getLocalizedMessage();
        String displayMessage = errorCode != null ? errorCodeRegister.getMessage(SpringUtils.getApplicationName(), errorCode.getCode(), exception.getArgs()) : exception.getLocalizedMessage();
        log.warn("Login Failure：error = {}", message);
        ApiResponseUtils.writeJsonResponse(response, ApiResponse.error(exception.getCode(), displayMessage), HttpServletResponse.SC_OK);
    }
}
